<template>
  <PageCard title="URL 编码/解码">
    <n-space vertical size="large">
      <!-- 操作选择 -->
      <n-radio-group v-model:value="operation" size="large">
        <n-space>
          <n-radio-button value="encode">编码</n-radio-button>
          <n-radio-button value="decode">解码</n-radio-button>
        </n-space>
      </n-radio-group>

      <!-- 字符集选择 -->
      <n-form-item label="字符集">
        <n-select 
          v-model:value="charset" 
          :options="charsetOptions"
          style="width: 200px"
        />
      </n-form-item>

      <!-- 输入输出区域 -->
      <n-grid :cols="21" :x-gap="16">
        <n-grid-item :span="10">
          <n-h3 class="text-center">{{ operation === 'encode' ? '原始文本' : 'URL编码文本' }}</n-h3>
          <n-input
            v-model:value="inputValue"
            type="textarea"
            :placeholder="operation === 'encode' ? '请输入要编码的文本' : '请输入要解码的URL编码文本'"
            :rows="15"
          />
        </n-grid-item>
        <n-grid-item :span="1" class="flex items-center justify-center">
          <n-button 
            type="primary" 
            size="large"
            circle
            @click="processData"
            :loading="loading"
            :disabled="!inputValue"
          >
            <template #icon>
              <n-icon :component="operation === 'encode' ? ArrowForward : ArrowBack" />
            </template>
          </n-button>
        </n-grid-item>
        <n-grid-item :span="10">
          <n-h3 class="text-center">{{ operation === 'encode' ? 'URL编码结果' : '解码结果' }}</n-h3>
          <n-input
            v-model:value="outputValue"
            type="textarea"
            :placeholder="operation === 'encode' ? '编码结果将显示在这里' : '解码结果将显示在这里'"
            :rows="15"
            readonly
          />
        </n-grid-item>
      </n-grid>

      <!-- 操作按钮 -->
      <n-space justify="end">
        <n-button @click="handleClear">
          <template #icon>
            <n-icon :component="ClearIcon" />
          </template>
          清空内容
        </n-button>
        <n-button type="primary" @click="handleCopy" :disabled="!outputValue">
          <template #icon>
            <n-icon :component="CopyIcon" />
          </template>
          复制结果
        </n-button>
      </n-space>


      <!-- 常见编码示例 -->
      <n-card title="常见字符编码对照">
        <n-table :bordered="false" :single-line="false">
          <thead>
            <tr>
              <th>原始字符</th>
              <th>URL编码（UTF-8）</th>
              <th>说明</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>空格</td>
              <td>%20</td>
              <td>URL中的空格</td>
            </tr>
            <tr>
              <td>!</td>
              <td>%21</td>
              <td>感叹号</td>
            </tr>
            <tr>
              <td>#</td>
              <td>%23</td>
              <td>井号（锚点符号）</td>
            </tr>
            <tr>
              <td>&</td>
              <td>%26</td>
              <td>参数分隔符</td>
            </tr>
            <tr>
              <td>=</td>
              <td>%3D</td>
              <td>参数赋值符</td>
            </tr>
            <tr>
              <td>你好</td>
              <td>%E4%BD%A0%E5%A5%BD</td>
              <td>中文示例</td>
            </tr>
          </tbody>
        </n-table>
      </n-card>
    </n-space>
    <n-divider />
    <UsageGuide
      :title="usageGuideConfig.title"
      :steps="usageGuideConfig.steps"
      :tips="usageGuideConfig.tips"
      :example="usageGuideConfig.example"
    />
  </PageCard>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useMessage, NIcon, NTable } from 'naive-ui';
import { ArrowBack, ArrowForward } from '@vicons/ionicons5';
import { CopyAllOutlined as CopyIcon, ClearOutlined as ClearIcon } from '@vicons/material';
import PageCard from "@/components/PageCard.vue";
import UsageGuide from "@/components/UsageGuide.vue";
import { CryptoApi } from '@/api/crypto';

const message = useMessage();

// 状态管理
const operation = ref<'encode' | 'decode'>('encode');
const charset = ref('UTF-8');
const inputValue = ref('');
const outputValue = ref('');
const loading = ref(false);

// UsageGuide configuration
const usageGuideConfig = {
  title: 'URL 编码/解码使用说明',
  steps: [
    '选择操作类型：编码或解码',
    '选择字符集（默认 UTF-8）',
    '在左侧输入框输入需要处理的内容',
    '点击中间的转换按钮',
    '右侧显示处理结果，可复制使用'
  ],
  tips: [
    'URL编码是一种编码机制，用于在URL中传输特殊字符',
    '编码时会将特殊字符转换为%加两位十六进制数的形式',
    '常见需要编码的字符：空格（%20）、中文、特殊符号等',
    '支持多种字符集编码，UTF-8是最常用的字符集',
    '在浏览器地址栏中，中文和特殊字符会自动进行URL编码'
  ],
  example: '原文：你好 世界! → URL编码：%E4%BD%A0%E5%A5%BD%20%E4%B8%96%E7%95%8C%21'
};

// 字符集选项
const charsetOptions = [
  { label: 'UTF-8', value: 'UTF-8' },
  { label: 'GBK', value: 'GBK' },
  { label: 'GB2312', value: 'GB2312' },
  { label: 'ISO-8859-1', value: 'ISO-8859-1' },
  { label: 'ASCII', value: 'ASCII' }
];

// 处理编码/解码
const processData = async () => {
  if (!inputValue.value) {
    message.warning('请输入要处理的内容');
    return;
  }

  loading.value = true;
  try {
    const response = await CryptoApi.urlProcess({
      content: inputValue.value,
      operation: operation.value,
      charset: charset.value
    });
    
    if (response.code === 200) {
      outputValue.value = response.data;
      message.success(`${operation.value === 'encode' ? '编码' : '解码'}成功`);
    } else {
      message.error(response.message || '操作失败');
    }
  } catch (error: any) {
    message.error(error.message || '网络错误，请检查服务是否正常');
  } finally {
    loading.value = false;
  }
};

// 清空内容
const handleClear = () => {
  inputValue.value = '';
  outputValue.value = '';
};

// 复制结果
const handleCopy = async () => {
  if (!outputValue.value) return;
  try {
    await navigator.clipboard.writeText(outputValue.value);
    message.success('结果已成功复制到剪贴板！');
  } catch (err) {
    message.error('复制失败，请手动复制');
  }
};
</script>

<style scoped>
.text-center {
  text-align: center;
  margin: 0 0 16px 0;
}

:deep(.n-table) {
  margin-top: 16px;
}

:deep(.n-table th) {
  font-weight: 600;
}

:deep(.n-table td) {
  font-family: monospace;
}
</style>